<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" id="input" />
  <div id="div"></div>
  <div class="div1"></div>
  <div class="div2"></div>
  <script>
    let obj = {}
    Object.defineProperty(obj, 'input', {
      get: function() {

      },
      set: function(val) {
        console.log(val)
        document.getElementById('div').innerHTML = val        
      }
    })
    document.getElementById('input').addEventListener('keyup', function () {
      obj.input = event.target.value
    })

    // 发布订阅模式 + 数据双向绑定 = 基本的响应式
    
    // 订阅器模型
    let Dep = {
      clientList: {},
      listen: function(key, fn) {
        (this.clientList[key] || (this.clientList[key] = [])).push(fn)
      },
      trigger: function() {
        console.log(Array.prototype.slice.call(arguments));
        let key = Array.prototype.shift.call(arguments),
        fns = this.clientList[key]
        console.log(key, "key")
        console.log(fns);
        console.log(this.clientList, 98);
        
        if (!fns || fns.length === 0) {
          return false
        }
        for (let i = 0, fn; fn = fns[i++];) {
          fn.apply(this, arguments)
        }
      }
    }

    // 数据劫持
    let dataHijack = function({data, tag, datakey, selector}) {
      let value = '',
      el = document.querySelector(selector)
      Object.defineProperty(data, datakey, {
        get: function() {
          return value
        },
        set: function(val) {
          value = val
          Dep.trigger(tag, val)
        }
      })
      // 添加订阅者
      Dep.listen(tag, function(text) {
        el.innerHTML = text
      })
    }

    let data = {}
    dataHijack({
      data,
      tag: 'view-1',
      datakey: 'one',
      selector: '.div1'
    })
    dataHijack({
      data,
      tag: 'view-2',
      datakey: 'two',
      selector: '.div2'
    })
    data.one = 3333
    data.two = 4444
  </script>
</body>
</html>